package com.fwj.user.service.user.rbac;

import com.alibaba.fastjson.JSONObject;
import com.fwj.core.common.common.CommonUtils;
import com.fwj.core.common.constant.DataConstant;
import com.fwj.core.common.execption.CommonException;
import com.fwj.core.common.model.PageRequest;
import com.fwj.core.common.model.PageResponse;
import com.fwj.core.common.model.ResponseDTO;
import com.fwj.core.common.model.ResponseEnum;
import com.fwj.user.api.rbac.RBACRoleService;
import com.fwj.user.dao.rbac.RBACRoleMapper;
import com.fwj.user.entity.rbac.role.Role;
import com.fwj.user.model.rbac.role.RoleVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.List;

/**
* @author root
* @description 针对表【rbac_role】的数据库操作Service实现
* @createDate 2022-05-01 16:41:39
*/
@Service
public class RBACRoleServiceImpl implements RBACRoleService {

    //添加日志工厂
    private static final Logger LOGGER = LoggerFactory.getLogger(RBACRoleServiceImpl.class);

    @Autowired
    private RBACRoleMapper rbacRoleMapper;

    @Override
    @Transactional
    public ResponseDTO saveRole(Role role) {
        try {
            Role execRole = buildRole(role);
            rbacRoleMapper.insertSelective(execRole);
            return new ResponseDTO().success();
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return new ResponseDTO().fail();
        }
    }

    private Role buildRole(Role role) {
        Role retRole = new Role();
        //生成角色编码
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
        String number = simpleDateFormat.format(timestamp) + CommonUtils.generateUniqueNumber();

        retRole.setRoleNumber(number);
        retRole.setRoleName(role.getRoleName());
        retRole.setCreator(role.getCreator());
        retRole.setCreateTime(timestamp);
        retRole.setUpdateTime(timestamp);
        retRole.setStatus(DataConstant.NORMAL);
        return retRole;
    }

    @Override
    @Transactional
    public ResponseDTO deleteRole(String roleNumber) {
        try {
            Example example = new Example(Role.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("roleNumber",roleNumber);
            rbacRoleMapper.deleteByExample(example);
            return new ResponseDTO().success();
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return new ResponseDTO().fail();
        }
    }

    @Override
    public ResponseDTO queryRole(JSONObject jsonObject) {
        try {
            PageRequest pageRequest = JSONObject.parseObject(jsonObject.toJSONString(),PageRequest.class);
            PageHelper.startPage(pageRequest.getPage(), pageRequest.getPageSize());
            Example example = buildRoleExample(pageRequest.getRequestBody());
            PageInfo<Role> pageInfo = new PageInfo<>(rbacRoleMapper.selectByExample(example));
            PageResponse<RoleVo> pageResponse = new PageResponse<>();
            pageResponse.setPageTotal(pageInfo.getTotal());
            List<RoleVo> roleVoList = JSONObject.parseArray(JSONObject.toJSONString(pageInfo.getList()),RoleVo.class);
            pageResponse.setResponseBody(roleVoList);
            return new ResponseDTO().success().setData(pageResponse);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return new ResponseDTO().fail();
        }
    }

    private Example buildRoleExample(JSONObject requestBody) {
        Example example = new Example(Role.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("status",DataConstant.NORMAL);
        if (CommonUtils.isEmpty(requestBody)){ return example; }
        RoleVo roleVo = JSONObject.parseObject(requestBody.toJSONString(),RoleVo.class);
        if (CommonUtils.isNotEmpty(roleVo.getRoleNumber())){
            criteria.andLike("roleNumber",roleVo.getRoleNumber());
        }
        if (CommonUtils.isNotEmpty(roleVo.getRoleName())){
            criteria.andLike("roleName",roleVo.getRoleName());
        }
        return example;
    }

    @Override
    public JSONObject getRoleDetails(String roleNumber) {
        try {
            Example example = new Example(Role.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("roleNumber",roleNumber);
            Role role = rbacRoleMapper.selectOneByExample(example);
            RoleVo roleVo = JSONObject.parseObject(JSONObject.toJSONString(role),RoleVo.class);
            return new ResponseDTO().success().setData(roleVo);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            return new ResponseDTO<>().fail();
        }
    }

    @Override
    public Role findRoleByRoleNumber(String roleNumber) {
        try {
            //构建Example查询参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("roleNumber",roleNumber);
            Example example = buildRoleExample(jsonObject);
            //如果查到多个数据则抛出异常
            return rbacRoleMapper.selectOneByExample(example);
        } catch (Exception e) {
            LOGGER.error(e.toString());
            throw new CommonException(ResponseEnum.SERVER_ERROR);
        }
    }

    @Override
    public List<Role> findRoleListByRoleId(List<Long> roleIdList) {
        List<Role> roleList = rbacRoleMapper.selectByIdList(roleIdList);
        return roleList;
    }

}
